import axios from "axios";
import { React, useEffect, useState } from "react";
import './header.css'
import { useNavigate } from "react-router";
import InterIP from '../IP/IP'
import ThreeAreas from "../threeareas";
import { Link } from "react-router-dom";
export default function Header() {
    const [userName, setUserName] = useState();
    const navigate = useNavigate();
    useEffect(() => {
        let IP = InterIP().props.children;
        if (document.cookie) {
            let UserId = document.cookie.slice(5);
            axios.post('http://' + IP + ':3000/user/selName', {
                user_id: UserId,
            }).then((res) => {
                setUserName((userName) => userName = res.data[0].user_name)
            })
        } else {
            setUserName((userName) => userName = '游客')
        }
    }, [])
    function addCookie(key, value, deadline) {
        // 如果 没有传入 key 或 value 或 deadline 则不必添加
        if (!(key && value && deadline)) return;
        // if (!(!key || !value || !deadline)) return;
        document.cookie = key + '=' + value + ';max-age=' + deadline;
    }
    function exit() {
        addCookie('user', '0', -1);
        navigate('/');
    }
    
    return (
        <div className="header">
            <div className="header_text">
                <div className="location">
                    <span>所在城市:</span>
                    <ThreeAreas/>
                    <span className="arrows">
                    </span>
                </div>
                <div className="user_msg">
                    <span>您好，{userName}</span>
                    <span>  </span>
                    <span className="exit" onClick={exit}>退出</span>|
                    <span><Link to="/home/person/myorder">我的订单</Link></span>|
                    <span><Link to="/home/person/mynews">我的消息</Link></span>|
                    <span>我是商家</span>|
                    <span>400-800-8820</span>
                </div>
            </div>
        </div>
    );
}